package com.yue.lin.service;

import com.yue.lin.domain.Permission;
import com.yue.lin.domain.Role;
import com.yue.lin.domain.User;
import com.yue.lin.repository.RoleRepository;
import com.yue.lin.repository.UserRepository;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    //添加用户
    @Override
    public User addUser(User user) {
        //加密方式
        String hashAlgorithmName = "MD5";
        user.setSalt(UUID.randomUUID().toString().replace("-", ""));
        //盐：为了即使相同的密码不同的盐加密后的结果也不同
        ByteSource byteSalt = ByteSource.Util.bytes(user.getSalt());
        //加密次数
        int hashIterations = 1024;
        SimpleHash result = new SimpleHash(hashAlgorithmName, user.getPassword(), byteSalt, hashIterations);
        user.setPassword(result.toString());
        userRepository.save(user);
        return user;
    }

    //查询用户通过用户名
    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}